package org.example.session.defaults;

import org.example.binding.MapperRegistry;
import org.example.executor.Executor;
import org.example.mapping.Environment;
import org.example.session.Configuration;
import org.example.session.SqlSession;
import org.example.session.SqlSessionFactory;
import org.example.session.TransactionIsolationLevel;
import org.example.transaction.Transaction;
import org.example.transaction.TransactionFactory;

import java.sql.SQLException;

/**
 * @Author: luyg
 * @Date: 2024/11/10/4:05
 * @Description:
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public SqlSession openSession() {
        Transaction tx = null;
        try {
            final Environment environment = configuration.getEnvironment();
            TransactionFactory transactionFactory = environment.getTransactionFactory();

            tx = transactionFactory.newTransaction(environment.getDataSource(), TransactionIsolationLevel.READ_COMMITTED, false);
            final Executor executor = configuration.newExecutor(tx);
            return new DefaultSqlSession(configuration,executor);
        }catch (Exception e){
            try {
                assert tx != null;
                tx.close();
            } catch (SQLException ignore) {
            }
            throw new RuntimeException("Error opening session.  Cause: " + e);
        }
    }
}
